var image = document.getElementById("coin");
var badFood = document.getElementById("badFood");
var high_scores = [];
$(document).ready(function() {
	//Canvas stuff
	var canvas = $("#canvas")[0];
	var ctx = canvas.getContext("2d");
	var w = $("#canvas").width();
	var h = $("#canvas").height();
	ctx.font = "30px Verdana";

	//Lets save the cell width in a variable for easy control
	var cw = 10;
	var d;
	var food;
	var score = 0;
	var foodTimer = 0;

	//Lets create the snake now
	var snake_array;
	//an array of cells to make up the snake

	function init() {
		d = "right";
		//default direction
		create_snake();
		create_food();
		//Now we can see the food particle
		//finally lets display the score
		score = 0;

		//Lets move the snake now using a timer which will trigger the paint function
		//every 60ms
		if ( typeof game_loop != "undefined")
			clearInterval(game_loop);
		game_loop = setInterval(paint, 60);
	}

	init();

	function create_snake() {
		var length = 5;
		//Length of the snake
		snake_array = [];
		//Empty array to start with
		for (var i = length - 1; i >= 0; i--) {
			//This will create a horizontal snake starting from the top left
			snake_array.push({
				x : i,
				y : 0
			});
		}
	}

	//Lets create the food now
	function create_food() {
		food = {
			x : Math.round(Math.random() * (w - cw) / cw),
			y : Math.round(Math.random() * (h - cw) / cw),
			foodTimer : foodTimer
		};
		//This will create a cell with x/y between 0-44
		//Because there are 45(450/10) positions accross the rows and columns
	}

	//Makes the background black, prints the appropriate high score text
	function highScores() {
		clearInterval(game_loop);
		ctx.fillStyle = "black";
		ctx.fillRect(0, 0, w, h);
		ctx.fillStyle = "white";
		ctx.fillText("High Scores", w / 2 - 100, 50);
		ctx.font = "10px Verdana";
		ctx.fillText("Hit \"Enter\" to reinitialize the game", w / 2 - 100, h - 20);
		ctx.font = "30px Verdana";
		//Insertion sort to order the array of scores in ascending order
		for (var i = 0, j, tmp; i < high_scores.length; ++i) {
			tmp = high_scores[i];
			for ( j = i - 1; j >= 0 && high_scores[j] > tmp; --j)
				high_scores[j + 1] = high_scores[j];
			high_scores[j + 1] = tmp;
		}
		var j = 0;
		//prints the scores in the appropriate location
		//accesses the indexes in reverse order because
		//the array is in ascending order
		for (var i = high_scores.length - 1; i >= 0; --i) {
			j++;
			ctx.fillText(high_scores[i], w / 2 - 75, 50 + j * 50);
		}
		//will clear the high_scores array after reaching 7 high scores
		if (high_scores.length == 7) {
			high_scores = [];
		}
	}

	//Lets paint the snake now
	function paint() {
		//Increments the foodTimer every 60ms with the game loop
		//The time is the amount of time before the food becomes badFood
		//Approximately 5 seconds
		food.foodTimer++;
		var time = 83.3333;

		//To avoid the snake trail we need to paint the BG on every frame
		//Lets paint the canvas now

		ctx.fillStyle = "aquamarine";
		ctx.fillRect(0, 0, w, h);
		ctx.strokeStyle = "black";
		ctx.strokeRect(0, 0, w, h);
		//The movement code for the snake to come here.
		//The logic is simple
		//Pop out the tail cell and place it infront of the head cell
		var nx = snake_array[0].x;
		var ny = snake_array[0].y;
		//These were the position of the head cell.
		//We will increment it to get the new head position
		//Lets add proper direction based movement now
		if (d == "right")
			nx++;
		else if (d == "left")
			nx--;
		else if (d == "up")
			ny--;
		else if (d == "down")
			ny++;

		//Lets add the game over clauses now
		//This will restart the game if the snake hits the wall
		//Lets add the code for body collision
		//Now if the head of the snake bumps into its body, the game will restart
		if (nx == -1 || nx == w / cw || ny == -1 || ny == h / cw || check_collision(nx, ny, snake_array)) {
			high_scores.push(score);
			highScores();
			//restarts game when Enter is pressed
			$(document).keypress(function(e) {
				if (e.keyCode == 13) {
					init();
				}
			});
			return;
		}

		//Lets write the code to make the snake eat the food
		//The logic is simple
		//If the new head position matches with that of the food,
		//Create a new head instead of moving the tail
		//If the head collides with the badFood then the player loses
		//a point and a body piece

		if (nx == food.x && ny == food.y && food.foodTimer < time) {
			var tail = {
				x : nx,
				y : ny
			};
			score++;
			console.log(snake_array.length);
			//Create new food
			create_food();
		} else if (nx == food.x && ny == food.y && food.foodTimer >= time) {
			snake_array.shift();
			console.log(snake_array.length);
			var tail = {
				x : nx,
				y : ny
			};
			score--;
			create_food();
		} else {
			var tail = snake_array.pop();
			//pops out the last cell
			tail.x = nx;
			tail.y = ny;
		}

		if (snake_array.length <= 0)
			highScores();
		//The snake can now eat the food.

		snake_array.unshift(tail);
		//puts back the tail as the first cell

		for (var i = 0; i < snake_array.length; i++) {
			var c = snake_array[i];
			//Lets paint 10px wide cells
			paint_cell(c.x, c.y);
		}

		//Lets paint the food
		//Thanks to Dara Diba for helping with this if statement
		if (food.foodTimer < time)
			ctx.drawImage(image, food.x * cw, food.y * cw, cw, cw);
		else if (food.foodTimer < time * 2)
			ctx.drawImage(badFood, food.x * cw, food.y * cw, cw, cw);
		else
			create_food();
		//Lets paint the score
		ctx.font = "10px Verdana";
		var score_text = "Score: " + score;
		ctx.fillText(score_text, 5, h - 5, 100);
		ctx.font = "30px Verdana";
	}

	//Lets first create a generic function to paint cells
	function paint_cell(x, y) {
		ctx.fillStyle = "red";
		ctx.fillRect(x * cw, y * cw, cw, cw);
		ctx.strokeStyle = "white";
		ctx.strokeRect(x * cw, y * cw, cw, cw);
	}

	function check_collision(x, y, array) {
		//This function will check if the provided x/y coordinates exist
		//in an array of cells or not
		for (var i = 0; i < array.length; i++) {
			if (array[i].x == x && array[i].y == y)
				return true;
		}
		return false;
	}

	//Lets add the keyboard controls now
	$(document).keydown(function(e) {
		var key = e.which;
		//We will add another clause to prevent reverse gear
		if (key == "37" && d != "right")
			d = "left";
		else if (key == "38" && d != "down")
			d = "up";
		else if (key == "39" && d != "left")
			d = "right";
		else if (key == "40" && d != "up")
			d = "down";
		//The snake is now keyboard controllable
	});

});
